﻿using AForge.Imaging.Filters;
using BoardBroker;
using ComLib.ComType;
using ComUIControl;
using CoreBroker;
using KWindow.KPageCore;
using LogLib;
using PhotoNamingService;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Forms;

namespace IPCPages
{
    public partial class PageDetectNoPass : PageControlBase
    {
        private BoardControl _board = BoardControl.Instance;
        private BaseResizeFilter _resizefilter = null;
        private List<TakenPhoto> listTakenPhotos = null;
        private Button buttonCancell = null;
        private Button buttonRetake = null;
        private PictureBox pictureBox1 = null;
        private PictureBox pictureBox2 = null;
        private Label labelReason1 = null;
        private Label labelReason2 = null;
        private ApplyTo _applyTo = ApplyTo.ExitAndEntry;
     
        public PageDetectNoPass()
        {
            _resizefilter = new ResizeBilinear(1000, 1200);
            InitializeComponent();
            SetProcessBase(ProcessDetectNoPass.Instance);
        }

        private void GetControls()
        {
            try
            {
                buttonCancell = GetControl<Button>("buttonCancell") as Button;
                buttonRetake = GetControl<Button>("buttonRetake") as Button;

                SetButtonDefaultStyles(buttonCancell);
                SetButtonDefaultStyles(buttonRetake);

                pictureBox1 = GetControl<PictureBox>("pictureBox1") as PictureBox;
                pictureBox2 = GetControl<PictureBox>("pictureBox2") as PictureBox;

                labelReason1 = GetControl<Label>("labelReason1") as Label;
                labelReason2 = GetControl<Label>("labelReason2") as Label;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                Log.WriteException(ex.ToString());
            }
        }
     
        public override void InitCtrls()
        {
            base.InitCtrls();
            GetControls();
        }

        public override void InitData()
        {
            _applyTo = Process.GetValue<ApplyTo>("ApplyTo");//照片类型
            _selectIndex = -1;
            listTakenPhotos = Process.GetValue<List<TakenPhoto>>("NoPassPhotos");
            if (listTakenPhotos == null || listTakenPhotos.Count <= 0)
            {
                MsgBox.Show("发生了意外的错误: 获取拍照结果为空!");
                ClearData();
                Process.ToHome();
                return;
            }
            if (!string.IsNullOrEmpty(listTakenPhotos[0].DestImagePath) && File.Exists(listTakenPhotos[0].DestImagePath))
            {
                //pictureBox1.Image = listTakenPhotos[0].DestImage;
                pictureBox1.Load(listTakenPhotos[0].DestImagePath);
            }
            labelReason1.Text = listTakenPhotos[0].NotPassReason;
            labelReason2.Text = ""; 
            if (listTakenPhotos.Count > 1) 
            {
                //if (listTakenPhotos[1].DestImage != null)
                //{
                //    pictureBox2.Image = listTakenPhotos[1].DestImage;
                //}
                if (!string.IsNullOrEmpty(listTakenPhotos[1].DestImagePath) && File.Exists(listTakenPhotos[1].DestImagePath))
                {
                    pictureBox2.Load(listTakenPhotos[1].DestImagePath);
                }

                labelReason2.Text = listTakenPhotos[1].NotPassReason;
            }
            
        }

        /// <summary>
        /// 清理窗体数据(窗体本次做完后)
        /// </summary>
        public override void ClearData()
        {
            base.ClearData();
            Process.RemoveKey("NoPassPhotos");
            labelReason1.Text = "";
            labelReason2.Text = "";
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
                pictureBox1.Image = null;
            }
            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
                pictureBox2.Image = null;
            }
        }

        /// <summary>
        /// 窗体关闭时
        /// </summary>
        public override void Close()
        {

        }

        public override void StartWork()
        {
            _board.StopWorking();
        }

        public override void StopWork()
        {
            base.StopWork();
        }

        protected override void btnCancel_Click(object sender, EventArgs e)
        {
            Log.WriteAsync("用户取消了拍照.");
            ClearData();
            _board.StopWorking();
            NotifyClientTakePhotoCancell();
            Process.ToHome();           
        }

        private void NotifyClientTakePhotoCancell()
        {
            if (Process.Job != null)
            {
                Process.Job.Cancel("用户选择了取消拍照.");
            }
        }

        private void buttonRetake_Click(object sender, EventArgs e)
        {
            Log.WriteAsync("用户点击了重拍.");
            ClearData();
            Process.ToAny("IPCPages.PageShowPreviewTips");  //PageMakePreparations
            //Process.ToAny("IPCPages.PageTakeAiming");//重拍时重新测量身高
        }

        public override void OnCountdownCompleted(object sender, EventArgs e)
        {
            int actionIndex = Process.GetValue<int>("ActionIndex");
            if (actionIndex > 3)
            {
                MsgBox.Show("由于您尝试了多次拍照依然检测不合格，\n请联系工作人员使用其他方式拍照.");
                Log.WriteAsync("重拍次数达到限定次数，中止拍照.");
                _board.StopWorking();
                NotifyClientTakePhotoCancell();
                base.OnCountdownCompleted(null, null);               
                return;
            }
            //Log.WriteAsync("倒计时结束: 自动进入重拍");
            //ClearData();
            //_motion.TurnOnWorkingLight();
            //Process.ToAny("IPCPages.PageMakePreparations");
        }

        /// <summary>
        /// 连续点击激活次数统计
        /// </summary>
        private int active_click_count1 = 0;

        /// <summary>
        /// 连续点击激活次数统计
        /// </summary>
        private int active_click_count2 = 0;

        private Stopwatch sw1 = new Stopwatch();

        private Stopwatch sw2 = new Stopwatch();

        private int _selectIndex = 0;
        public override void UpdateData()
        {
            if(_selectIndex < 0)
            {
                return;
            }
            TakenPhoto photo = listTakenPhotos[_selectIndex];
            TakenPhoto OnlyPhoto = photo.Clone() as TakenPhoto;
            //保存选中的照片
            Process.SetValue("TakenPhoto", OnlyPhoto);
            Process.SetValue("ZZZPPath", OnlyPhoto.DestImagePath);
            string inParams = "";
            IDCardAll info = Process.GetValue<IDCardAll>("IDCardInfo");
            if (info != null)
            {
                inParams = info.number;
            }
            string srcFile = OnlyPhoto.DestImagePath;
            string serialNumber = _config.CreatSerialNumber(inParams);
            Log.WriteAsync($"生成照片序列号:{serialNumber}");
            // 生成照片序列号
            SD.SetValue("PhotoSerialNumber", serialNumber);
            string personDir = _config.OutputDirs[serialNumber];
            Process.SetValue("PersonDataDirectory", personDir);
            string fileName = serialNumber + ".jpg";
            string destFile = Path.Combine(personDir, fileName);
            if (!PhotoNamingBase.Option.EnableOverride)
            {
                if (File.Exists(destFile))
                {
                    throw new Exception("已存在同名照片。由于设置了不可覆盖，本次保存被取消。\n如果需要继续正常使用，请联系管理员修改操作选项。");
                }
            }
            try
            {
                File.Copy(srcFile, destFile, true);
                Log.WriteAsync("制证照片已保存到个人数据目录:" + destFile);
            }
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
                string error = "复制文件发生了异常:\n" + ex.Message;
                MessageBox.Show(error);
            }

            // 保存现场人像
            if (UserAction == UserApplyAction.TakePhotoAndWeiYinTB
                || UserAction == UserApplyAction.TakePhotoAndYSL)
            {
                try
                {
                    string liveportraitFile = Path.Combine(personDir, "LivePortrait.jpg");
                    //Bitmap liveportraitImage = _resizefilter.Apply(OnlyPhoto.SourceImage);
                    // liveportraitImage.Save(liveportraitFile, ImageFormat.Jpeg);
                    File.Copy(OnlyPhoto.SourceImagePath, liveportraitFile);
                    Log.WriteAsync("现场人像照片已保存到个人数据目录:" + liveportraitFile);
                   // liveportraitImage.Dispose();
                    //liveportraitImage = null;
                    Process.SetValue("Liveportrait", liveportraitFile);
                }
                catch (Exception ex)
                {
                    Log.WriteException(ex.ToString());
                    string error = "保存现场人像照片发生了异常:\n" + ex.Message;
                    MessageBox.Show(error);
                }
            }
        }

        private bool OnForceSelected()
        {
            if(_selectIndex<0)
            {
                return false;
            }
            TakenPhoto photo = listTakenPhotos[_selectIndex];
            if(!photo.QCPass)
            {
                MsgBox.Show("选中的照片质检不合格，不能上传.");
                return false;
            }
            FormConfirm form = new FormConfirm(listTakenPhotos[_selectIndex].DestImagePath);
            if(form.ShowDialog() == DialogResult.OK)
            {
                ForceToNext();
                return true;
            }
            return false;
        }

        private void ForceToNext()
        {
            if (_selectIndex < 0)
            {
                return;
            }
            try
            {              
                UpdateData();
                Log.WriteAsync($"用户选择上传第{_selectIndex}张不合格照片");
                ClearData();
                _board.StopWorking();
                Process.ToAny("IPCPages.PageUploading");
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存照片发生了异常!\n" + ex.Message);
                Log.WriteException(ex.ToString());
                return;
            }            
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if(_applyTo != ApplyTo.PortVisa)
            {
                return;
            }
            if (!sw1.IsRunning)
            {
                sw1.Restart();
                return;
            }
            if (sw1.ElapsedMilliseconds > 2000)
            {
                sw1.Reset();
                active_click_count1 = 0;
            }
            else
            {
                active_click_count1++;
            }
            if (active_click_count1 == 2)
            {
                sw1.Reset();
                active_click_count1 = 0;
                _selectIndex = 0;
                OnForceSelected();
            }
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            if (_applyTo != ApplyTo.PortVisa)
            {
                return;
            }
            if (!sw2.IsRunning)
            {
                sw2.Restart();
                return;
            }
            if (sw2.ElapsedMilliseconds > 2000)
            {
                sw2.Reset();
                active_click_count2 = 0;
            }
            else
            {
                active_click_count2++;
            }
            if (active_click_count2 == 2)
            {
                sw2.Reset();
                active_click_count2 = 0;
                _selectIndex = 1;
                OnForceSelected();
            }
        }
    }
}
